package com.third.customer.site.support;

import com.third.customer.site.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.NamedThreadLocal;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by hehuaichun on 2020/6/25.
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
    private NamedThreadLocal<Long> accessStartTime = new NamedThreadLocal<>("access_start_time");

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String httpOrigin = request.getHeader("Origin");

        log.info("paramsMap:{}", request.getParameterMap());
        if (!StringUtils.isEmpty(httpOrigin)) {
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS");
            response.setHeader("Access-Control-Allow-Origin", httpOrigin);
            response.setHeader("Access-Control-Allow-Headers",
                    "Origin, X-Requested-With, Content-Type, Accept, Authorization, Access-Token, Third-token");
        } else {
            response.setHeader("Access-Control-Allow-Origin", "*");
        }
        response.setHeader("Access-Control-Expose-Headers", Constants.THIRD_TOKEN);

        accessStartTime.set(System.currentTimeMillis());
        return true;
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {
        long current = System.currentTimeMillis();
        long use = current - accessStartTime.get();

        String url = null;
        if (null != request.getRequestURL()) {
            url = request.getRequestURL().toString();
        }
        String qs = request.getQueryString() == null ? "" : "?" + request.getQueryString();
        String method = request.getMethod();

        log.info("{} {}{} {}ms", method, url, qs, use);
    }
}
